package com.dzl.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.FileSystems;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import com.alipay.api.internal.util.file.IOUtils;
import com.dzl.aliyunoss.ALiYunOSSConstant;
import com.dzl.util.wx.WxUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dzl.constant.UploadConstant;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.thoughtworks.xstream.core.util.Base64Encoder;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Positions;
import sun.misc.BASE64Encoder;

/**
 * 图片生成缩略图
 *
 * @author lujianmin
 */
public class ImageUtils {
    private final static Logger logger = LoggerFactory.getLogger(ImageUtils.class);
    private String srcFile;
    private String destFile;
    private int width;
    private int height;
    private Image img;

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    //二维码相关
    private static int qr_width = 200; // 图像宽度
    private static int qr_height = 200; // 图像高度
    private static String qr_format = "png";// 图像类型

    // 获取img标签正则
    private static final String IMGURL_REG = "<img.*src=(.*?)[^>]*?>";
    // 获取src路径的正则
    private static final String IMGSRC_REG = "(http|https):\"?(.*?)(\"|>|\\s+)";

    /**
     * chkImgExt:检查图片后缀是否合法
     *
     * @param ext
     * @return
     */
    public static boolean chkImgExt(String ext) {
        if (ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg") || ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase(".gif") || ext.equalsIgnoreCase(".bmp")) {
            return true;
        }
        return false;
    }

    /**
     * chkFileExt:检查文件后缀是否合法
     *
     * @param ext
     * @return
     */
    public static boolean chkFileExt(String ext) {
        if (ext.equalsIgnoreCase("zip") || ext.equalsIgnoreCase("rar")) {
            return true;
        }
        return false;
    }

    /**
     * 构造函数
     *
     * @param srcPath String
     * @throws IOException
     */
    public ImageUtils(String srcPath, String destPath) throws IOException {
        File _file = new File(srcPath); // 读入文件
        this.srcFile = srcPath;
        this.destFile = destPath;
        img = ImageIO.read(_file); // 构造Image对象
        width = img.getWidth(null); // 得到源图宽
        height = img.getHeight(null); // 得到源图长
    }

    /**
     * 强制压缩/放大图片到固定的大小
     *
     * @param w int 新宽度
     * @param h int 新高度
     * @throws IOException
     */
    public void resize(int w, int h) throws IOException {
        /*
         * BufferedImage _image = new BufferedImage(w, h,
         * BufferedImage.TYPE_INT_RGB);
         * _image.getGraphics().drawImage(img.getScaledInstance(w, h,
         * Image.SCALE_SMOOTH), 0, 0, null);
         * //_image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
         * FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
         * JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
         * encoder.encode(_image); // 近jpeg编码 out.close();
         */
        String ext = getExtName(srcFile);
        int transparency = Transparency.OPAQUE;
        if ("png".equalsIgnoreCase(ext)) {
            transparency = Transparency.TRANSLUCENT;
        }
        BufferedImage _image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = _image.createGraphics();
        _image = g2d.getDeviceConfiguration().createCompatibleImage(w, h, transparency);
        g2d.dispose();
        _image.getGraphics().drawImage(img.getScaledInstance(w, h, Image.SCALE_SMOOTH), 0, 0, null);

        try {
            ImageIO.write(_image, ext, new File(destFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 按照固定的比例缩放图片
     *
     * @param t double 比例
     * @throws IOException
     */
    public void resize(double t) throws IOException {
        int w = (int) (width * t);
        int h = (int) (height * t);
        resize(w, h);
    }

    /**
     * 以宽度为基准，等比例放缩图片
     *
     * @param w int 新宽度
     * @throws IOException
     */
    public void resizeByWidth(int w) throws IOException {
        int h = (int) (height * w / width);
        resize(w, h);
    }

    /**
     * 以高度为基准，等比例缩放图片
     *
     * @param h int 新高度
     * @throws IOException
     */
    public void resizeByHeight(int h) throws IOException {
        int w = (int) (width * h / height);
        resize(w, h);
    }

    /**
     * 按照最大高度限制，生成最大的等比例缩略图
     *
     * @param w int 最大宽度
     * @param h int 最大高度
     * @throws IOException
     */
    public void resizeFix(int w, int h) throws IOException {
        if (width / height > w / h) {
            resizeByWidth(w);
        } else {
            resizeByHeight(h);
        }
    }

    /**
     * 设置目标文件名 setDestFile
     *
     * @param fileName String 文件名字符串
     */
    public void setDestFile(String fileName) throws Exception {
        if (!fileName.endsWith(".jpg")) {
            throw new Exception("Dest File Must end with \".jpg\".");
        }
        destFile = fileName;
    }

    /**
     * 获取目标文件名 getDestFile
     */
    public String getDestFile() {
        return destFile;
    }

    /**
     * 获取图片原始宽度 getSrcWidth
     */
    public int getSrcWidth() {
        return width;
    }

    /**
     * 获取图片原始高度 getSrcHeight
     */
    public int getSrcHeight() {
        return height;
    }

	/*public static void main(String[] args) {
		try {
			ImageUtils pic = new ImageUtils("C:/Users/Administrator/Desktop/170103113419817678.jpg", "C:/Users/Administrator/Desktop/170103113419817678.jpg");
			//ImageUtils pic = new ImageUtils("E:/work/upload/test/test01.png");
			pic.resizeByWidth(50);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/

    /**
     * 生成二维码不带logo
     *
     * @param content
     * @param imgPath
     */
    public static void createQrcode(String content, String imgPath) {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qr_width, qr_height, hints);// 生成矩阵
            MatrixToImageWriter.writeToPath(bitMatrix, qr_format, FileSystems.getDefault().getPath(UploadConstant.UPL_DIR, imgPath));// 输出图像
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("生成二维码图片错误");
        }
    }

    /**
     * 生成二维码带logo
     *
     * @param content
     * @param imgPath
     * @param logoPath
     * @throws Exception
     */
    public static void createQrcodeWithLogo(String content, String imgPath, String logoPath) {
        HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        File qrcodeFile = FileSystems.getDefault().getPath(UploadConstant.UPL_DIR, imgPath).toFile();
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qr_width, qr_height, hints);
            writeToFile(bitMatrix, qr_format, qrcodeFile, logoPath);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("生成二维码图片错误");
        }
    }

    /**
     * 获取小程序码（圆形）
     * @Author: liuguanjun
     * @Date 2021/09/06 16:25
     * @param scene 二维码参数
     * @param appId 小程序appid
     * @param appSecret 小程序app密钥
     * @param appletHomePath 小程序页面路径
     */
    public static String getWxCode(String scene,String appId,String appSecret,String appletHomePath) {
        //返回的文件网络位置
        String filePath = "";
        try {
            InputStream in = WxUtils.getQRCode(scene,appletHomePath,appId,appSecret);
            filePath = UploadUtil.uploadPic(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(filePath);
        return filePath;
    }

    /**
     * 小程序获取普通二维码（正方形）
     * @Author: liuguanjun
     * @Date 2021/09/14 10:40
     * @param path 跳转路径，可带参数
     * @param appId 小程序appid
     * @param appSecret 小程序app密钥
     */
    public static String getWxCode(String path,String appId,String appSecret) {
        //返回的文件网络位置
        String filePath = "";
        try {
            InputStream in = WxUtils.getQRCode(path,appId,appSecret);
            filePath = UploadUtil.uploadPic(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(filePath);
        return filePath;
    }

    /**
     * @param matrix   二维码矩阵相关
     * @param format   二维码图片格式
     * @param file     二维码图片文件
     * @param logoPath logo路径
     * @throws IOException
     */
    private static void writeToFile(BitMatrix matrix, String format, File file, String logoPath) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        Graphics2D gs = image.createGraphics();

        Image img = ImageIO.read(new File(logoPath));   //载入logo

        int widthLogo = img.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10) : img.getWidth(null), heightLogo = img.getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10) : img.getWidth(null);

        int x = (image.getWidth() - widthLogo) / 2, y = (image.getHeight() - heightLogo) / 2;

        gs.drawImage(img, x, y, widthLogo, heightLogo, null);
        gs.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
        gs.setStroke(new BasicStroke(2));
        gs.setColor(Color.WHITE);
        gs.drawRect(x, y, widthLogo, heightLogo);

        gs.dispose();
        img.flush();
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }


    public static String getImageStr(String destUrl) {
        HttpURLConnection httpUrl = null;
        byte[] data = null;
        DataInputStream in = null;
        try {
            URL url = new URL(destUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            in = new DataInputStream(httpUrl.getInputStream());
            data = new byte[httpUrl.getContentLength()];
            in.readFully(data);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }
        }
        Base64Encoder encoder = new Base64Encoder();
        return encoder.encode(data);
    }

    /**
     * 通过图片的url获取图片的byte[]
     *
     * @param imgUrl 图片url
     * @return 返回图片byte[]
     */
    public static byte[] image2Base64(String imgUrl) {

        URL url = null;

        InputStream is = null;

        HttpURLConnection httpUrl = null;

        try {

            url = new URL(imgUrl);

            httpUrl = (HttpURLConnection) url.openConnection();

            httpUrl.connect();

            httpUrl.getInputStream();

            is = httpUrl.getInputStream();

			return IOUtils.toByteArray(is);

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (is != null) {

                try {

                    is.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (httpUrl != null) {

                httpUrl.disconnect();

            }

        }

        return null;

    }

    /***
     * 获取ImageSrc地址
     *
     * @param listImageUrl
     * @return
     */
    public static List<String> getImageSrc(List<String> listImageUrl) {
        List<String> listImgSrc = new ArrayList<String>();
        for (String image : listImageUrl) {
            Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(image);
            while (matcher.find()) {
                listImgSrc.add(matcher.group().substring(0, matcher.group().length() - 1));
            }
        }
        return listImgSrc;
    }

    /**
     * 截取凭证图片src
     */
    public static String subImage(String proof) {
        List<String> proofs = null;
        if (!EmptyUtils.isEmpty(proof)) {
            proofs = new ArrayList<String>();
            proofs.add(proof);
        } else {
            return null;
        }
        List<String> proof_src = null;
        //修改图片格式
        List<String> imageUrlStr = ImageUtils.getImageSrc(proofs);
        if (imageUrlStr != null && imageUrlStr.size() > 0) {
            proof_src = new ArrayList<String>();
            for (String string : imageUrlStr) {
                proof_src.add(string.substring(string.indexOf("upload_dz/", 0) + 10, string.length()));
            }
        } else {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (String s : proof_src) {
            sb.append(s + ",");
        }
        return sb.substring(0, sb.lastIndexOf(","));
    }

    public static List<String> getImageUrlStr(String content) {
        List<String> list = new ArrayList<String>();
        //目前img标签标示有3种表达式
        //<img alt="" src="1.jpg"/> <img alt="" src="1.jpg"></img> <img alt="" src="1.jpg">
        //开始匹配content中的<img />标签
        Pattern p_img = Pattern.compile("<(img|IMG)(.*?)(/>|></img>|>)");
        Matcher m_img = p_img.matcher(content);
        boolean result_img = m_img.find();
        if (result_img) {
            while (result_img) {
                //获取到匹配的<img />标签中的内容
                String str_img = m_img.group(2);
                //开始匹配<img />标签中的src
                Pattern p_src = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
                Matcher m_src = p_src.matcher(str_img);
                if (m_src.find()) {
                    String str_src = m_src.group(3);
                    list.add(str_src);
                }
                //匹配content中是否存在下一个<img />标签，有则继续以上步骤匹配<img />标签中的src
                result_img = m_img.find();
            }
        }/*else {//可能是文字
    		Pattern p_text = Pattern.compile("<p.*?>(.*?)</p>");
        	Matcher m_text = p_text.matcher(content);
        	boolean result_text = m_text.find();
        	if(result_text) {
        		while (result_text) {
        	    	//获取到匹配的<p />标签中的内容
        	    	String str_text = m_text.group(1);
        	    	list.add(str_text);
        	    	//匹配content中是否存在下一个<p />标签，有则继续以上步骤匹配<p />标签中的src
        	    	result_text = m_text.find();
        	    	}
        	}
    	}*/
        return list;
    }

/*    public static void main(String[] args) throws IOException {
    	File fromPic=new File("C:\\Users\\Administrator\\Desktop\\1.png");
        File toPic=new File("C:\\Users\\Administrator\\Desktop\\2.png");
        long start = System.currentTimeMillis();
        Thumbnails.of(fromPic).size(300,300).toFile(toPic);
        System.out.println(System.currentTimeMillis() - start + "毫秒");
	}*/

    public void testHandlePicture() throws IOException {

        //创建图片文件(此处为1024×768px的图片)和处理后的图片文件
        File fromPic = new File("C:\\Users\\Administrator\\Desktop\\定制链形象墙.png");
        File toPic = new File("C:\\Users\\Administrator\\Desktop\\定制链形象墙压缩.png");
        File waterPic = new File("picture/水印图片.jpg");//作为水印的图片

        //用outputFormat(图像格式)转换图片格式，保持原尺寸不变
        Thumbnails.of(fromPic).scale(1f).outputFormat("png").toFile("picture/png格式的图片.png");


        //按指定大小把图片进行缩和放（会遵循原图高宽比例）
        //此处把图片压成400×500的缩略图
        Thumbnails.of(fromPic).size(400, 500).toFile(toPic);//变为400*300,遵循原图比例缩或放到400*某个高度

        //按照比例进行缩小和放大
        Thumbnails.of(fromPic).scale(0.2f).toFile(toPic);//按比例缩小
        Thumbnails.of(fromPic).scale(2f);//按比例放大

        //不按比例，就按指定的大小进行缩放
        Thumbnails.of(fromPic).size(100, 100).keepAspectRatio(false).toFile(toPic);
        //或者Thumbnails.of(fromPic).forceSize(100,100).toFile(toPic);

        //旋转图片，rotate(角度),正数则为顺时针，负数则为逆时针
        Thumbnails.of(fromPic).size(200, 200).rotate(90).toFile(toPic);

        //图片尺寸不变，压缩图片文件大小outputQuality实现,参数1为最高质量
        Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);

        //给图片加水印，watermark(位置，水印图，透明度)Positions.CENTER表示加在中间
        Thumbnails.of(fromPic).size(400, 400)
                .watermark(Positions.CENTER, ImageIO.read(waterPic), 0.5f)
                .outputQuality(0.8f).toFile(toPic);

        //用sourceRegion()实现图片裁剪
        //图片中心300*300的区域,Positions.CENTER表示中心，还有许多其他位置可选
        Thumbnails.of(fromPic).sourceRegion(Positions.CENTER, 300, 300).size(300, 300).toFile(toPic);

        //图片中上区域300*300的区域
        Thumbnails.of(fromPic).sourceRegion(Positions.TOP_CENTER, 300, 300).size(300, 300).toFile(toPic);

        //输出成文件流OutputStream
        OutputStream os = new FileOutputStream(toPic);
        Thumbnails.of(fromPic).size(120, 120).toOutputStream(os);

        //输出BufferedImage,asBufferedImage()返回BufferedImage
        BufferedImage bi = Thumbnails.of(fromPic).size(120, 120).asBufferedImage();
        ImageIO.write(bi, "jpg", toPic);

        //压缩至指定图片尺寸（例如：横400高300），保持图片不变形，多余部分裁剪掉(这个是引的网友的代码)
        BufferedImage image = ImageIO.read(fromPic);
        Builder<BufferedImage> builder = null;

        int imageWidth = image.getWidth();
        int imageHeitht = image.getHeight();
        if ((float) 300 / 400 != (float) imageWidth / imageHeitht) {
            if (imageWidth > imageHeitht) {
                image = Thumbnails.of(fromPic).height(300).asBufferedImage();
            } else {
                image = Thumbnails.of(fromPic).width(400).asBufferedImage();
            }
            builder = Thumbnails.of(image).sourceRegion(Positions.CENTER, 400, 300).size(400, 300);
        } else {
            builder = Thumbnails.of(image).size(400, 300);
        }
        builder.outputFormat("jpg").toFile(toPic);
    }
	/* public static void main(String[] args) throws UnsupportedEncodingException {
		 String imgURL="http://39.106.35.171:8080/upload_dz/ueditor/image/20190425/1556173181619003344.png";
		 String srtname="";
     	String fileHeard="";
     	if(imgURL.indexOf("order/")>-1) {
     		srtname = imgURL.substring(imgURL.lastIndexOf("order/") + 6);
     		fileHeard=imgURL.substring(0,imgURL.lastIndexOf("order/")+6);
     	}else if(imgURL.indexOf("image/")>-1) {
     		srtname = imgURL.substring(imgURL.lastIndexOf("image/") + 6);
     		fileHeard=imgURL.substring(0,imgURL.lastIndexOf("image/")+6);
     	}
     	String[] strArr=srtname.split("/");
     	String filePath="";
     	for(String str:strArr) {
     		filePath+=URLEncoder.encode(str,"utf-8")+"/";
     	}
     	filePath = fileHeard+filePath.substring(0,filePath.lastIndexOf("/"));
     	//System.out.println(filePath);
		System.out.println(ImageUtils.GetImageStrFromUrl(imgURL));
	}*/

    /***
     * 获取ImageSrc地址
     * @param imageUrl
     * @return
     */
    public static String setImageSrc(String imageUrl) {
        StringBuffer sb = new StringBuffer("");

        //如果不为空
        if (imageUrl != null && !"".equals(imageUrl)) {
            if (imageUrl.indexOf(",") > -1) {//多张图片
                for (String img : imageUrl.split(",")) {
                    //如果包含HTTP，信息，直接返回，不处理
                    if (!img.contains("http") && !img.contains("https")) {
                        //拼接对应的URL，正式或测试
                        if (img.contains("-img/")) {
                            sb.append(ALiYunOSSConstant.FILE_LOCATION);
                        } else {
                            sb.append(UploadConstant.URL);
                        }
                        if (img.contains("http://")) {
                            img = img.replace("http", "https");
                        }
                        if (img.contains("dzl-mall-upload.oss-cn-beijing.aliyuncs.com")) {
                            img = img.replace("dzl-mall-upload.oss-cn-beijing.aliyuncs.com", "img.dingzhilian.com");
                        }
                        sb.append(img).append(",");
                    }
                }
                if (EmptyUtils.isEmpty(sb.toString())) {
                    return imageUrl.split(",")[0];
                } else {
                    return sb.substring(0, sb.length() - 1);
                }
            } else {//单张图片
                if (!imageUrl.contains("http") && !imageUrl.contains("https")) {
                    //拼接对应的URL，正式或测试
                    if (imageUrl.contains("-img/")) {
                        sb.append(ALiYunOSSConstant.FILE_LOCATION);
                    } else {
                        sb.append(UploadConstant.URL);
                    }
                }
                if (imageUrl.contains("http://")) {
                    imageUrl = imageUrl.replace("http", "https");
                }
                if (imageUrl.contains("dzl-mall-upload.oss-cn-beijing.aliyuncs.com")) {
                    imageUrl = imageUrl.replace("dzl-mall-upload.oss-cn-beijing.aliyuncs.com", "img.dingzhilian.com");
                }
                sb.append(imageUrl);
            }
        }
        return sb.toString();
    }

    /**
     * 得到网页中图片的地址
     */
    public static String getImgStr(String htmlStr) {
        StringBuilder pics = new StringBuilder();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        // String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.append(m.group(1)).append(",");
            }
        }
        return pics.substring(0, pics.length() - 1);
    }

    /**
     * 判断是否是上传图片
     *
     * @param value
     * @param defaultValue
     * @return
     */
    public static Boolean toBoolean(String value, Boolean defaultValue) {
        if (!EmptyUtils.isEmpty(value)) {
            value = value.trim().toLowerCase();
            if ("1".equals(value) || "true".equals(value))
                return Boolean.TRUE;
            else if ("0".equals(value) || "false".equals(value))
                return Boolean.FALSE;
        }
        return defaultValue;
    }

    /**
     * getSmallUrl:根据大图路径生成缩略图路径
     *
     * @param url
     * @return
     * @author lujm
     */
    public static String getSmallUrl(String url) {
        if (url != null && url.length() > 0) {
            int dot = url.lastIndexOf(".");
            if (dot > -1) {
                return url.substring(0, dot) + "." + "s" + "."
                        + url.substring(dot + 1);
            } else {
                return url;
            }
        }
        return "";
    }

    /**
     * @param fileExt 后缀名
     * @return
     * @Description 获取新的文件名 命名格式：yyyyMMddHHmmssSSS_三位随机数
     */
    public static String getNewFileName(String fileExt) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fullPath = df.format(new Date()) + "_"
                + new Random().nextInt(1000) + "." + fileExt;
        return fullPath;
    }

    /**
     * @param filename
     * @return
     * @Title: getExtName
     * @Description: 获取文件扩展名
     */
    public static String getExtName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return "";
    }

    /**
     * 本地文件（图片、excel等）转换成Base64字符串
     *
     * @param imgPath
     */
    public static String convertFileToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            System.out.println("文件大小（字节）=" + in.available());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组进行Base64编码，得到Base64编码的字符串
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);
        return base64Str;
    }
}
